package grpcUtils

import (
	"context"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"
	"log"
)

type IGrpc interface {
	RegisterFromEndpoint(gatewayAddr string, handles ...gateWayHandle)
	RegisterServer(handles func(s grpc.ServiceRegistrar))
}

type GrpcGinClient struct {
	grpcAddr string
	Conn     *grpc.ClientConn
	mux      *runtime.ServeMux
}

func (g *GrpcGinClient) RegisterFromEndpoint(gatewayAddr string, handles ...gateWayHandle) {
	//批量注册
	ctx := context.Background()
	for _, item := range handles {
		item(ctx, g.mux, gatewayAddr)
	}
}
func (g *GrpcGinClient) Close() {
	g.Conn.Close()
}
func (g *GrpcGinClient) RegisterClient(handle func(cc grpc.ClientConnInterface)) {
	handle(g.Conn)
}

func NewGrpcGinClient(grpcAddr string, opts ...grpc.DialOption) *GrpcGinClient {
	conn, err := grpc.Dial(grpcAddr, opts...)
	if err != nil {
		log.Fatalf("failed to connect: %v", err)
	}
	return &GrpcGinClient{
		grpcAddr, conn,
		runtime.NewServeMux(),
	}
}
